package com.dong.jdk8.thread.problem;

import java.util.Hashtable;
import java.util.Map.Entry;

/**
 * 在遍历过程中，如果已经遍历的数组上的内容变化了，迭代器会抛出ConcurrentModificationException异常
 * @author jianyang206881
 * @date 2018/2/22
 */
public class HashtableTest {
    private static Hashtable<String, String> hashtable = new Hashtable<>(10);

    public static void main(String[] args) {
        while (true) {
            for (int i = 0; i < 10; i++) {
                System.out.println("添加字符串:" + i);
                hashtable.put("字符串:" + i, "字符串:" + i);
            }

            Thread removeThread = new Thread(() -> {
                for (Entry<String, String> entry : hashtable.entrySet()) {
                    System.out.println("removeThread删除:" + entry.getKey());
                    hashtable.remove(entry.getKey());
                }
            });

            Thread printThread = new Thread(() -> {
                for (Entry<String, String> entry : hashtable.entrySet()) {
                    System.out.println("printThread获取:" + entry.getKey());
                }
            });

            removeThread.start();
            printThread.start();

            //不要同时产生过多的线程，否则会导致操作系统假死
            while (Thread.activeCount() > 20) ;
        }
    }
}
